#include<iostream>
using namespace std;


struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* pcur = head;
        if (pcur == nullptr || pcur->next == nullptr) {
            return head;
        }
        ListNode* pnext = head->next;
        ListNode* root = new ListNode(-1, head);
        ListNode* ppre = root;
        int flag = 0;

        while (pnext != nullptr) {
            while (pnext != nullptr && pcur->val == pnext->val) {
                // pcur->next = pnext->next;
                // delete pnext;
                // pnext = pcur->next;
                ppre->next = pcur->next;
                delete pcur;
                pcur = pnext;
                pnext = pnext->next;
                flag = 1;
            }
            if (flag == 1) {
                flag = 0;
                ppre->next = pcur->next;
                delete pcur;
                pcur = pnext;
                if (pnext != nullptr) pnext = pnext->next;
            }
            else if (pnext != nullptr) {
                ppre = ppre->next;
                pcur = pnext;
                pnext = pnext->next;
            }
        }
        head = root->next;
        return root->next;
    }
};